import {
  getNewCartGoods,
  mergeCart,
  findCart,
  insertCart,
  deleteCart,
  updateCart,
  checkAllCart
} from '@/api/cart'
const state = () => {
  return {
    list: []
  }
}
const mutations = {
  // 加入购物车
  insertCart (state, payload) {
    // 考虑两种情况：
    //  情况1：已经添加过的商品(skuid已存在)，是数量的累加
    //  情况2：没有添加过的就添加到列表前
    const index = state.list.findIndex(item => item.skuId === payload.skuId)
    if (index >= 0) {
      state.list[index].count += payload.count
    } else {
      state.list.unshift(payload)
    }
    // state.list.push(payload)
  },
  // 更新购物车
  updateCart (state, goods) {
    // console.log(goods)
    const updategoods = state.list.find(item => item.skuId === goods.skuId)
    if (!updategoods) return
    for (const key in goods) {
      if (
        goods[key] !== undefined ||
          goods[key] !== null ||
          goods[key] !== ''
      ) {
        updategoods[key] = goods[key]
      }
    }
  },
  // 删除购物车商品
  deleteCart (state, skuId) {
    console.log(skuId)
    const index = state.list.findIndex(item => item.skuId === skuId)
    state.list.splice(index, 1)
  },
  // 设置购物车列表
  setCartList (state, list) {
    state.list = list
  }
}
// actions-------------------------------------------------------------------
const actions = {
  insertCart (store, goods) {
    return new Promise((resolve, reject) => {
      if (store.rootState.user.profile.token) {
        // console.log(store.rootState)
        insertCart(goods).then(() => {
          store.dispatch('findCartList')
          resolve()
        })
      } else {
        store.commit('insertCart', goods)
        resolve()
      }
    })
  },
  // 修改购物车商品
  updateCart (store, goods) {
    // goods中字段有可能不完整，goods有的信息才去修改。
    // 1. goods中必需又skuId，才能找到对应的商品信息
    return new Promise((resolve, reject) => {
      if (store.rootState.user.profile.token) {
        // console.log(store.rootState)
        updateCart(goods).then(() => {
          store.dispatch('findCartList')
          resolve()
        })
      } else {
        store.commit('updateCart', goods)
        resolve()
      }
    })
  },
  // 获取最新的购物车列表
  findCartList (store) {
    return new Promise((resolve, reject) => {
      if (store.rootState.user.profile.token) {
        // 登录 TODO
        findCart().then(({ result }) => {
          store.commit('setCartList', result)
          resolve()
        })
      } else {
        store.state.list.forEach(async item => {
          // console.log(item)
          const { result } = await getNewCartGoods(item.skuId)
          // console.log(result)
          store.commit('updateCart', {
            skuId: item.skuId,
            ...result
          })
          resolve()
        })
      }
    })
  },
  // 删除购物车商品
  deleteCart (store, skuId) {
    return new Promise((resolve, reject) => {
      if (store.rootState.user.profile.token) {
        // 登录 TODO
        deleteCart([skuId]).then(() => {
          store.dispatch('findCartList')
        })
        resolve()
      } else {
        // 本地
        store.commit('deleteCart', skuId)
        resolve()
      }
    })
  },
  // 做有效商品的全选&反选
  checkAllCart (store, selected) {
    return new Promise((resolve, reject) => {
      if (store.rootState.user.profile.token) {
        // 登录 TODO
        const ids = store.getters.validList.map(item => item.skuId)
        checkAllCart({ selected, ids }).then(() => {
          store.dispatch('findCartList')
        })
        resolve()
      } else {
        // 本地
        // 1. 获取有效的商品列表，遍历的去调用修改mutations即可
        store.getters.validList.forEach(item => {
          item.selected = selected
          store.commit('updateCart', item)
        })
        resolve()
      }
    })
  },
  // 批量删除选中商品
  batchDeleteCart (store, isClear) {
    return new Promise((resolve, reject) => {
      if (store.rootState.user.profile.token) {
        // 登录 TODO
        const ids = store.getters[
          isClear === true ? 'invalidList' : 'selectedList'
        ].map(item => item.skuId)
        // console.log(ids)
        deleteCart(ids).then(() => {
          store.dispatch('findCartList')
        })
        resolve()
      } else {
        // 本地
        // 1. 获取选中商品列表，进行遍历调用deleteCart mutataions函数
        store.getters[
          isClear === true ? 'invalidList' : 'selectedList'
        ].forEach(item => {
          store.commit('deleteCart', item.skuId)
        })
        resolve()
      }
    })
  },
  // 修改sku规格函数
  updateCartSku (store, { oldSkuId, newSku }) {
    return new Promise((resolve, reject) => {
      if (store.rootState.user.profile.token) {
        // 登录 TODO
        // 登录 TODO
        // 1. 获取原先商品的数量
        // 2. 删除原先商品
        // 3. 获取修改的skuId 和 原先商品数量 做一个加入购物车操作
        // 4. 更新列表
        const oldGoods = store.state.list.find(item => item.skuId === oldSkuId)
        deleteCart([oldSkuId])
          .then(() => {
            return insertCart({ skuId: newSku.skuId, count: oldGoods.count })
          })
          .then(() => {
            store.dispatch('findCartList')
          })
        resolve()
      } else {
        // 本地
        // 但你修改了sku的时候其实skuId需要更改，相当于把原来的信息移出，创建一条新的商品信息。
        // 1. 获取旧的商品信息
        // console.log(oldSkuId)
        const oldGoods = store.state.list.find(item => item.skuId === oldSkuId)
        // console.log(oldGoods)
        // console.log(newSku)
        // 2. 删除旧的商品
        store.commit('deleteCart', oldSkuId)
        // 3. 合并一条新的商品信息
        const {
          skuId,
          price: nowPrice,
          oldPrice: price,
          inventory: stock,
          specsText: attrsText
        } = newSku
        const newGoods = {
          ...oldGoods,
          skuId,
          nowPrice,
          stock,
          attrsText,
          price
        }
        // 4. 去插入即可
        store.commit('insertCart', newGoods)
      }
    })
  },
  // 合并本地购物车
  async mergeLocalCart (store) {
    // 存储token后调用合并API接口函数进行购物合并
    const cartList = store.getters.validList.map(
      ({ skuId, selected, count }) => {
        return { skuId, selected, count }
      }
    )
    await mergeCart(cartList)
    const { result } = await findCart()
    // 合并成功将本地购物车删除
    store.commit('setCartList', result)
  }
}
// getters -----------------------------------------------------------------
const getters = {
  // 有效商品列表
  validList (state) {
    return state.list.filter(item => item.stock > 0 && item.isEffective)
  },
  // 有效商品件数
  validTotal (state, getters) {
    return getters.validList.reduce((p, c) => p + c.count, 0)
  },
  // 有效商品总金额
  validAmount (state, getters) {
    return (
      getters.validList.reduce((p, c) => p + c.nowPrice * 100 * c.count, 0) /
      100
      // 因为这里有小数相加的问题 相加之后会有很小的小数出现 这是语言的问题
      // 先扩大 再缩小就可以了
    )
  },
  // 无效商品列表
  invalidList (state) {
    return state.list.filter(item => !(item.stock > 0 && item.isEffective))
  },
  // 选中商品列表
  selectedList (state, getters) {
    return getters.validList.filter(item => item.selected)
  },
  // 选中商品件数
  selectedTotal (state, getters) {
    return getters.selectedList.reduce((p, c) => p + c.count, 0)
  },
  // 选中商品总金额
  selectedAmount (state, getters) {
    return getters.selectedList.reduce((p, c) => p + (c.nowPrice * 100 * c.count), 0) / 100
  },
  // 是否全选
  isCheckAll (state, getters) {
    return getters.validList.length === getters.selectedList.length && getters.selectedList.length !== 0
  }
}
export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
}
